package com.pine.service.pineframework.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.pine.common.beans.exception.BusinessException;
import com.pine.common.beans.exception.ExceptionCodeEnum;
import com.pine.common.beans.pineframework.request.SysRoleMenuQueryRequest;
import com.pine.common.beans.pineframework.response.SysRoleMenuQueryResponse;
import com.pine.common.beans.request.IdRequest;
import com.pine.common.beans.request.PageRequest;
import com.pine.common.beans.response.PageResponse;
import com.pine.dao.pineframework.entity.SysRoleMenu;
import com.pine.manager.pineframework.SysRoleMenuManager;
import com.pine.manager.pineframework.bo.SysRoleMenuBo;
import com.pine.manager.pineframework.convertors.SysRoleMenuConvertor;
import com.pine.manager.pineframework.query.SysRoleMenuQuery;
import com.pine.service.pineframework.SysRoleMenuService;
import com.pine.service.util.PageUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 角色菜单表 服务实现类
 * </p>
 *
 * @author pine manage
 * @since 2024-08-12
 */
@Slf4j
@Service
public class SysRoleMenuServiceImpl implements SysRoleMenuService {

    @Resource
    private SysRoleMenuManager sysRoleMenuManager;

    @Resource
    private SysRoleMenuConvertor sysRoleMenuConvertor;

    private static final Map<String, SFunction<SysRoleMenu, ?>> COLUMNS_FUNCTION_MAP;

    static {
        COLUMNS_FUNCTION_MAP = Map.of(
                "id", SysRoleMenu::getId
        );
    }


    /**
     * 通过唯一key查询单个数据
     *
     * @param uniqueKey 唯一键
     * @param column    列名
     * @return 单个数据查询响应结果
     */
    @Override
    public SysRoleMenuQueryResponse getOneByUniqueKey(Object uniqueKey, String column) {
        // 根据业务ID查询
        SysRoleMenuBo sysRoleMenuBo = sysRoleMenuManager.getOneByUniqueKey(uniqueKey, COLUMNS_FUNCTION_MAP.getOrDefault(column, SysRoleMenu::getId));
        return sysRoleMenuConvertor.entityBoToQueryResponse(sysRoleMenuBo);
    }

    /**
     * 查询信息（不分页）
     *
     * @param request 请求
     * @return 响应
     */
    @Override
    public List<SysRoleMenuQueryResponse> list(SysRoleMenuQueryRequest request) {
        SysRoleMenuQuery sysRoleMenuQuery = sysRoleMenuConvertor.queryRequestToQuery(request);
        if (ObjectUtils.isNotEmpty(sysRoleMenuQuery)) {
            List<SysRoleMenuBo> sysRoleMenuList = sysRoleMenuManager.list(sysRoleMenuQuery);
            if (ObjectUtils.isNotEmpty(sysRoleMenuList)) {
                return sysRoleMenuList.stream()
                        .map(sysRoleMenuConvertor::entityBoToQueryResponse)
                        .filter(ObjectUtils::isNotEmpty)
                        .collect(Collectors.toList());
            }
        }
        return Collections.emptyList();
    }


    /**
     * 查询信息（分页）
     *
     * @param request 请求
     * @return PageResponse 响应
     */
    @Override
    public PageResponse<SysRoleMenuQueryResponse> listPages(PageRequest<SysRoleMenuQueryRequest> request) {
        try {
            // 分页查询
            IPage<SysRoleMenuBo> sysRoleMenuPage = sysRoleMenuManager.page(transformToQuery(request));

            // 安全地处理分页转换逻辑
            return safelyConvertPage(sysRoleMenuPage);
        } catch (Exception e) {
            log.error("查询失败", e);
            throw new BusinessException(ExceptionCodeEnum.SELECT_ERROR);
        }
    }


    /**
     * 安全地将分页数据转换为响应对象
     *
     * @param sysRoleMenuPage 分页查询结果
     * @return 分页响应对象
     */
    private PageResponse<SysRoleMenuQueryResponse> safelyConvertPage(IPage<SysRoleMenuBo> sysRoleMenuPage) {
        if (sysRoleMenuPage == null || sysRoleMenuPage.getRecords() == null) {
            return new PageResponse<>();
        }

        // 使用并行流进行转换以提高效率，但需确保线程安全
        List<SysRoleMenuQueryResponse> responses = sysRoleMenuPage.getRecords().parallelStream()
                .map(sysRoleMenuBo -> sysRoleMenuConvertor.entityBoToQueryResponse(sysRoleMenuBo))
                .collect(Collectors.toList());

        return PageUtil.convertPage(sysRoleMenuPage, responses);
    }


    /**
     * 将请求 request 转换成 manager 的 query 对象
     *
     * @param request 请求参数
     * @return query 对象
     */
    private PageRequest<SysRoleMenuQuery> transformToQuery(PageRequest<SysRoleMenuQueryRequest> request) {
        SysRoleMenuQuery sysRoleMenuQuery = sysRoleMenuConvertor.queryRequestToQuery(request.getData());
        return new PageRequest<>(request.getPageNum(), request.getPageSize(), sysRoleMenuQuery);
    }

    /**
     * 根据角色ID获取菜单ID集合
     *
     * @param request 请求体
     * @return 响应
     */
    @Override
    public List<Long> getMenuIdsByRoleId(IdRequest<Long> request) {
        Long roleId = request.getId();
        if (ObjectUtil.isEmpty(roleId)) {
            return Collections.emptyList();
        }

        // 查询角色菜单信息
        SysRoleMenuQuery query = new SysRoleMenuQuery();
        query.setRoleId(roleId);
        List<SysRoleMenuBo> sysRoleMenuBos = sysRoleMenuManager.list(query);
        if (ObjectUtil.isEmpty(sysRoleMenuBos)) {
            return Collections.emptyList();
        }

        return sysRoleMenuBos.stream()
                .map(SysRoleMenuBo::getMenuId)
                .collect(Collectors.toList());
    }
}
